package com.xy6.concurrencyart.chapter01;

/**
 * 测试并行执行是否一定比串行执行快
 * 
 * <pre>
 * 对于CPU密集型任务，并行执行不能显著提高执行速度
 * 为什么并发执行的速度会比串行慢呢？这是因为线程有创建和上下文切换的开销。
 * </pre>
 * 
 * @author zhang
 * @since 2018-05-16
 */
public class ConcurrencyTest {

	private static final long count = 100000001;
	private static final long times = 1;

	/**
	 * 1w: 
	 * serial avg: 843 ms
	 * concurrency avg: 1860 ms
	 * 
	 * 10w: 
	 * serial avg: 7381 ms
	 * concurrency avg: 21517 ms
	 * 
	 * @param args
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws InterruptedException {
		testSerial();
		testConcurrency();
	}

	private static void testConcurrency() throws InterruptedException {
		long start = System.currentTimeMillis();
		for (int i = 0; i < times; i++) {
			concurrency();
		}
		long time = System.currentTimeMillis() - start;
		System.out.println(String.format("concurrency avg: %d ms", time));
	}

	private static void testSerial() throws InterruptedException {
		long start = System.currentTimeMillis();
		for (int i = 0; i < times; i++) {
			serial();
		}
		long time = System.currentTimeMillis() - start;
		System.out.println(String.format("serial avg: %d ms", time));
	}

	/**
	 * 并行执行一个计算任务
	 * 
	 * @throws InterruptedException
	 */
	@SuppressWarnings("unused")
	private static void concurrency() throws InterruptedException {
		Thread thread = new Thread(new Runnable() {
			@Override
			public void run() {
				int a = 0;
				for (long i = 0; i < count; i++) {
					a += 5;
				}
			}
		});
		thread.start();
		int b = 0;
		for (long i = 0; i < count; i++) {
			b--;
		}
		thread.join();
	}

	/**
	 * 串行执行一个计算任务
	 */
	@SuppressWarnings("unused")
	private static void serial() {
		int a = 0;
		for (long i = 0; i < count; i++) {
			a += 5;
		}
		int b = 0;
		for (long i = 0; i < count; i++) {
			b--;
		}
	}

}
